import { base64src } from '../utils/base64ToSrc'
Page({
  data: {
    accessToken: '',
    picPath: '',
    imgUrl: ''
  },
  onShow() {
    this.getAccessToken()
  },
  toUploadPic() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        const tempFilePaths = res.tempFilePaths
        that.setData({imgUrl: tempFilePaths[0]})
        // 图片转base64
        const imgbase = wx.getFileSystemManager().readFileSync(tempFilePaths[0], "base64")
        that.getDealPic(imgbase)
      }
    })
  },
  getAccessToken() {
    const that = this
    wx.request({
      method: 'POST',
      url: 'https://aip.baidubce.com/oauth/2.0/token',
      data: {
        'grant_type': 'client_credentials',
        'client_id': 'qzsaKY0Zu1aGawK15LkH25y8',
        'client_secret': 'Izv0vq7o03fCji5Luc3ZuzaieZLVe63G'
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        that.setData({
          accessToken: res.data.access_token
        })
      }
    })
  },
  getDealPic(imgbase) {
    wx.showLoading({title: '处理中', mask: true})
    const that = this
    wx.request({
      method: 'POST',
      url: 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime',
      data : {
        access_token: that.data.accessToken,
        image: imgbase,
        type: 'anime_mask',
        mask_id:"1"
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        wx.hideLoading()
        if (res.data.image) {
          const imgData = `data:image/jpeg;base64,${res.data.image}`
          base64src(imgData, res => {
            that.setData({
              picPath:imgData
            })
          },
          ),
          console.log(imgData)
        } else {
          wx.showToast({
            title: '处理失败，请重试~'
          })
        }
      }
    })
  }
  
})